package com.ruoyi.web.controller.energy;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.energy.domain.EmsDevice;
import com.ruoyi.energy.domain.EmsTimeSeriesData;
import com.ruoyi.energy.service.IEmsDeviceService;
import com.ruoyi.energy.service.ITDengineTimeSeriesService;

/**
 * 设备管理Controller
 * 
 * @author ruoyi
 * @date 2024-01-20
 */
@RestController
@RequestMapping("/energy/device")
public class EmsDeviceController extends BaseController {
    
    @Autowired
    private IEmsDeviceService emsDeviceService;

    @Autowired
    private ITDengineTimeSeriesService tdengineTimeSeriesService;

    /**
     * 查询设备列表
     */
    @PreAuthorize("@ss.hasPermi('energy:device:list')")
    @GetMapping("/list")
    public TableDataInfo list(EmsDevice emsDevice) {
        startPage();
        List<EmsDevice> list = emsDeviceService.selectEmsDeviceList(emsDevice);
        return getDataTable(list);
    }

    /**
     * 导出设备列表
     */
    @PreAuthorize("@ss.hasPermi('energy:device:export')")
    @Log(title = "设备管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, EmsDevice emsDevice) {
        List<EmsDevice> list = emsDeviceService.selectEmsDeviceList(emsDevice);
        ExcelUtil<EmsDevice> util = new ExcelUtil<EmsDevice>(EmsDevice.class);
        util.exportExcel(response, list, "设备数据");
    }

    /**
     * 获取设备详细信息
     */
    @PreAuthorize("@ss.hasPermi('energy:device:query')")
    @GetMapping(value = "/{deviceId}")
    public AjaxResult getInfo(@PathVariable("deviceId") Long deviceId) {
        return success(emsDeviceService.selectEmsDeviceByDeviceId(deviceId));
    }

    /**
     * 新增设备
     */
    @PreAuthorize("@ss.hasPermi('energy:device:add')")
    @Log(title = "设备管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody EmsDevice emsDevice) {
        return toAjax(emsDeviceService.insertEmsDevice(emsDevice));
    }

    /**
     * 修改设备
     */
    @PreAuthorize("@ss.hasPermi('energy:device:edit')")
    @Log(title = "设备管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody EmsDevice emsDevice) {
        return toAjax(emsDeviceService.updateEmsDevice(emsDevice));
    }

    /**
     * 删除设备
     */
    @PreAuthorize("@ss.hasPermi('energy:device:remove')")
    @Log(title = "设备管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deviceIds}")
    public AjaxResult remove(@PathVariable Long[] deviceIds) {
        return toAjax(emsDeviceService.deleteEmsDeviceByDeviceIds(deviceIds));
    }

    /**
     * 获取设备导入模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<EmsDevice> util = new ExcelUtil<EmsDevice>(EmsDevice.class);
        util.importTemplateExcel(response, "设备数据");
    }

    /**
     * 导入设备数据
     */
    @PreAuthorize("@ss.hasPermi('energy:device:import')")
    @Log(title = "设备管理", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<EmsDevice> util = new ExcelUtil<EmsDevice>(EmsDevice.class);
        List<EmsDevice> deviceList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = emsDeviceService.importDevice(deviceList, updateSupport, operName);
        return success(message);
    }

    /**
     * 校验设备编码
     */
    @PostMapping("/checkDeviceCodeUnique")
    public boolean checkDeviceCodeUnique(@RequestBody EmsDevice emsDevice) {
        return emsDeviceService.checkDeviceCodeUnique(emsDevice);
    }

    /**
     * 根据部门查询设备
     */
    @PreAuthorize("@ss.hasPermi('energy:device:list')")
    @GetMapping("/listByDept/{deptId}")
    public AjaxResult listByDept(@PathVariable("deptId") Long deptId) {
        List<EmsDevice> list = emsDeviceService.selectEmsDeviceListByDeptId(deptId);
        return success(list);
    }

    /**
     * 生成设备MQTT提交格式
     */
    @PreAuthorize("@ss.hasPermi('energy:device:list')")
    @GetMapping("/mqtt-format/{deviceId}")
    public AjaxResult generateMqttFormat(@PathVariable("deviceId") Long deviceId) {
        EmsDevice device = emsDeviceService.selectEmsDeviceByDeviceId(deviceId);
        if (device == null) {
            return error("设备不存在");
        }

        Map<String, Object> mqttFormat = emsDeviceService.generateMqttFormat(device);
        return success(mqttFormat);
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('energy:device:edit')")
    @Log(title = "设备管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody EmsDevice emsDevice) {
        return toAjax(emsDeviceService.updateEmsDevice(emsDevice));
    }

    /**
     * 获取设备选择框列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect(EmsDevice emsDevice) {
        List<EmsDevice> devices = emsDeviceService.selectEmsDeviceList(emsDevice);
        return success(devices);
    }

    // ==================== TDengine数据查询接口 ====================

    /**
     * 查询设备最新数据
     */
    @PreAuthorize("@ss.hasPermi('energy:device:query')")
    @GetMapping("/data/latest/{deviceCode}")
    public AjaxResult getDeviceLatestData(@PathVariable String deviceCode) {
        try {
            EmsTimeSeriesData data = tdengineTimeSeriesService.selectLatestDataByDevice(deviceCode);
            return success(data);
        } catch (Exception e) {
            return error("查询设备最新数据失败: " + e.getMessage());
        }
    }

    /**
     * 查询设备历史数据
     */
    @PreAuthorize("@ss.hasPermi('energy:device:query')")
    @GetMapping("/data/history/{deviceCode}")
    public AjaxResult getDeviceHistoryData(@PathVariable String deviceCode,
                                          @RequestParam String startTime,
                                          @RequestParam String endTime,
                                          @RequestParam(defaultValue = "1") Integer pageNum,
                                          @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            Date start = DateUtils.parseDate(startTime);
            Date end = DateUtils.parseDate(endTime);

            int offset = (pageNum - 1) * pageSize;
            List<EmsTimeSeriesData> data = tdengineTimeSeriesService.selectHistoryDataByDeviceWithPage(
                deviceCode, start, end, pageSize, offset);

            // 查询总数
            long total = tdengineTimeSeriesService.countDeviceData(deviceCode, start, end);

            TableDataInfo dataTable = new TableDataInfo();
            dataTable.setRows(data);
            dataTable.setTotal(total);

            return success(dataTable);
        } catch (Exception e) {
            return error("查询设备历史数据失败: " + e.getMessage());
        }
    }

    /**
     * 查询设备聚合数据
     */
    @PreAuthorize("@ss.hasPermi('energy:device:query')")
    @GetMapping("/data/aggregated/{deviceCode}")
    public AjaxResult getDeviceAggregatedData(@PathVariable String deviceCode,
                                             @RequestParam String startTime,
                                             @RequestParam String endTime,
                                             @RequestParam(defaultValue = "1h") String interval) {
        try {
            Date start = DateUtils.parseDate(startTime);
            Date end = DateUtils.parseDate(endTime);

            List<Map<String, Object>> data = tdengineTimeSeriesService.selectAggregatedDataByDevice(
                deviceCode, start, end, interval);

            return success(data);
        } catch (Exception e) {
            return error("查询设备聚合数据失败: " + e.getMessage());
        }
    }

    /**
     * 查询所有设备最新数据
     */
    @PreAuthorize("@ss.hasPermi('energy:device:list')")
    @GetMapping("/data/latest/all")
    public AjaxResult getAllDevicesLatestData() {
        try {
            List<EmsTimeSeriesData> data = tdengineTimeSeriesService.selectAllDevicesLatestData();
            return success(data);
        } catch (Exception e) {
            return error("查询所有设备最新数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取设备状态统计
     */
    @PreAuthorize("@ss.hasPermi('energy:device:list')")
    @GetMapping("/status/statistics")
    public AjaxResult getDeviceStatusStatistics() {
        try {
            Map<String, Object> statistics = new HashMap<>();

            // 获取所有设备的最新状态
            List<EmsTimeSeriesData> latestData = tdengineTimeSeriesService.selectAllDevicesLatestData();

            // 统计各种状态的设备数量
            long online = 0;
            long offline = 0;
            long alarm = 0;
            long fault = 0;

            for (EmsTimeSeriesData data : latestData) {
                if (data.getStatus() != null) {
                    String status = data.getStatus().toUpperCase();
                    switch (status) {
                        case "0":
                        case "ONLINE":
                            online++;
                            break;
                        case "1":
                        case "ALARM":
                            alarm++;
                            break;
                        case "2":
                        case "FAULT":
                            fault++;
                            break;
                        case "3":
                        case "OFFLINE":
                            offline++;
                            break;
                        default:
                            offline++;
                            break;
                    }
                } else {
                    offline++;
                }
            }

            statistics.put("online", online);
            statistics.put("offline", offline);
            statistics.put("alarm", alarm);
            statistics.put("fault", fault);

            return success(statistics);
        } catch (Exception e) {
            return error("获取设备状态统计失败: " + e.getMessage());
        }
    }

    /**
     * 查询设备在线状态统计
     */
    @PreAuthorize("@ss.hasPermi('energy:device:list')")
    @GetMapping("/statistics/online")
    public AjaxResult getDeviceOnlineStatistics() {
        try {
            Map<String, Long> statistics = tdengineTimeSeriesService.selectDeviceOnlineStatistics();
            return success(statistics);
        } catch (Exception e) {
            return error("查询设备在线状态统计失败: " + e.getMessage());
        }
    }

    /**
     * 查询设备能耗排行榜
     */
    @PreAuthorize("@ss.hasPermi('energy:device:query')")
    @GetMapping("/ranking/energy")
    public AjaxResult getDeviceEnergyRanking(@RequestParam String energyType,
                                           @RequestParam String startTime,
                                           @RequestParam String endTime,
                                           @RequestParam(defaultValue = "10") Integer limit) {
        try {
            Date start = DateUtils.parseDate(startTime);
            Date end = DateUtils.parseDate(endTime);

            List<Map<String, Object>> ranking = tdengineTimeSeriesService.selectDeviceEnergyRanking(
                energyType, start, end, limit);

            return success(ranking);
        } catch (Exception e) {
            return error("查询设备能耗排行榜失败: " + e.getMessage());
        }
    }
}